package com.ck567.automationtesting

import com.ck567.automationtesting.entity.Book
import com.ck567.automationtesting.service.Service
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.runner.RunWith
import org.mockito.BDDMockito
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import java.lang.Exception
import java.time.LocalDate
import javax.annotation.Resource

@RunWith(SpringRunner::class)
@SpringBootTest
@AutoConfigureMockMvc
class AutomationTestingApplicationTests {

    @Resource
    lateinit var mockMvc: MockMvc

    // 隔离 -> 打桩
    @MockBean
    lateinit var service: Service

    @Test
    @Throws(Exception::class)
    fun bookApiTest() {
        val title = "java learning"
        // mockbean 开始模拟
        bookServiceMockBean(title)
        // mockbean 模拟完成
        val expect =
            "{\"title\":\"java learning\",\"author\":\"dax\",\"price\":78.56,\"releaseTime\":\"2018-03-22\"}"
        mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/books")
            .param("title", title))
            .andExpect(MockMvcResultMatchers.content()
                .json(expect))
            .andDo(MockMvcResultHandlers.print())
        // mockbean 重置
    }

    @Test
    fun bookServiceTest() {
        val title = "java learning"
        // 调用此方法，  若使用@MockBean注解，则表示要代理service方法
        // 在此处调用代理方法，若未调用此方法，
        // 或后续调用service中方法与此方法中调用service方法传参数不一致，则会无法加载返回对象，同时也就无法加载对象中的属性。
        bookServiceMockBean(title);
        Assertions.assertThat(service.queryByTitle(title).title).isEqualTo(title)
    }

    private fun bookServiceMockBean(title: String) {
        val book = Book()
        book.author = "dax"
        book.price = 78.56
        book.releaseTime = LocalDate.of(2018, 3, 22)
        book.title = title

        BDDMockito.given(service.queryByTitle(title)).willReturn(book)
//        BDDMockito.doReturn(book).`when`(
//            service?.queryByTitle(title)
//        )
    }
}
